/**
 * 
 */
package cn.ivicar.app.controller.customer;

import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;
import com.sun.jersey.core.header.FormDataContentDisposition;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.sae.SaeUtils;
import cn.com.carsmart.sae.subject.Subject;
import cn.com.carsmart.sae.token.UsernamePasswordDomainToken;
import cn.com.carsmart.ws.model.Customer;
import cn.ivicar.app.controller.util.DateUtil;
import cn.ivicar.passport.controller.CaptchaController;
import cn.ivicar.passport.controller.PassportController;
import cn.ivicar.passport.controller.utils.SexEnum;
import net.sf.json.JSONObject;

/**
 * 管理用户信息
 * @author liurunbin 2017年5月17日 cn.ivicar.app.controller.customer
 */
public class UserController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

	@Inject
	private PassportController passportController;
	@Inject
	private CaptchaController captchaController;

	public JSONObject captchaEffective(String mobile, String captcha, String bizType) throws CarsmartException {
		boolean effective = captchaController.validateCaptcha(mobile, captcha, bizType);

		JSONObject result = new JSONObject();
		result.put("effective", effective);
		return result;
	}

	public JSONObject mobileExist(String mobile) throws CarsmartException {
		boolean exist = passportController.mobileExist(mobile);

		JSONObject result = new JSONObject();
		result.put("exist", exist);
		return result;
	}

	public JSONObject oAuthLogin(String username, String password) throws CarsmartException {

		// 登陆鉴权
		passportController.oAuthByMobile(username, password);

		// 用户登陆信息存入缓存
		UsernamePasswordDomainToken token = new UsernamePasswordDomainToken(username, password, null);
		SaeUtils.getContext().getSubject().login(token);

		JSONObject object = new JSONObject();
		// TODO:获取token的待定
		object.put("token", SecurityUtils.getSubject().getSession().getId());
		LOGGER.info(String.format("用户[%s]登录鉴权结束", username));
		return object;

	}
	
	public JSONObject debugLogin(String username) throws CarsmartException {

		// 登陆鉴权
		Customer c = passportController.getByMobile(username);
		if(c == null){
			throw new BadRequestException("400", "用户不存在");
		}

		// 用户登陆信息存入缓存
		UsernamePasswordDomainToken token = new UsernamePasswordDomainToken(username, "", null);
		SaeUtils.getContext().getSubject().login(token);

		JSONObject object = new JSONObject();
		// TODO:获取token的待定
		object.put("token", SecurityUtils.getSubject().getSession().getId());
		LOGGER.info(String.format("用户[%s]登录鉴权结束", username));
		return object;

	}

	public void register(String mobile, String password, String captcha) throws CarsmartException {
		passportController.register(mobile, captcha, password);

	}

	/**
	 * 用户退出
	 *
	 * @param request
	 * @throws CarsmartException
	 */
	public void logout(long customerId) throws CarsmartException {

		LOGGER.info(String.format("用户[customerId=%s]退出登录", customerId));

		Subject subject = SaeUtils.getContext().getSubject();
		if (subject != null) {
			subject.logout();
		}
	}

	public void updatePwd(Long customerId, String oldPwd, String newPwd, String newPwdRepeat) throws CarsmartException {
		if (StringUtils.isBlank(oldPwd)) {
			throw new BadRequestException("common", "请输入原始密码！");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BadRequestException("common", "请输入新密码！");
		}
		if (oldPwd.equals(newPwd)) {
			throw new BadRequestException("common", "原密码与新密码不能相同！");
		}
		if (StringUtils.isBlank(newPwdRepeat)) {
			throw new BadRequestException("common", "请再次输入密码！");
		}
		if (!newPwd.equals(newPwdRepeat)) {
			throw new BadRequestException("common", "两次录入的新密码不一致！");
		}

		passportController.modifyPassword(customerId, oldPwd, newPwdRepeat);

	}

	public boolean resetPasswordByCode(String mobile, String password, String captcha) throws CarsmartException {

		return passportController.resetPasswordByCode(mobile, password, captcha);
	}

	public boolean modifyMobileByCodeAndPassword(Long customerId, String oldMobile, String newMobile, String password,
			String captcha) throws CarsmartException {

		// 修改手机号鉴权
		passportController.oAuthByMobile(oldMobile, password);
		passportController.modifyMobile(newMobile, captcha);
		// 将用户登陆信息重新存入缓存
		UsernamePasswordDomainToken token = new UsernamePasswordDomainToken(newMobile, password, null);
		SaeUtils.getContext().getSubject().login(token);

		return true;
	}

	public JSONObject getCustomerInfo(Long customerId) throws CarsmartException {
		Customer customer = passportController.get(customerId);
		return customerToJson(customer);
	}

	private JSONObject customerToJson(Customer customer) throws CarsmartException {
		if (customer == null) {
			throw new BadRequestException("common", "customer不能为空！");
		}

		JSONObject result = new JSONObject();

		result.put("userId", customer.getId() != null ? customer.getId() : "");
		result.put("nickname", customer.getNickname() != null ? customer.getNickname() : "");
		result.put("mobile", customer.getMobile() != null ? customer.getMobile() : "");
		result.put("head", customer.getHead() != null ? customer.getHead() : "");
		result.put("sex", getSex(customer.getSex()));
		result.put("birthday",
				customer.getBirthday() != null ? DateUtil.DATEFORMATER2().format(customer.getBirthday()) : "");

		return result;
	}

	private String getSex(String sex) {

		if(StringUtils.isBlank(sex)){
			return "";
		}
		Integer index;
		try {
			index = Integer.valueOf(sex);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return SexEnum.get(index).getValue();

	}

	/**
	 * 客户信息的修改
	 *
	 * @param obj
	 * @throws CarsmartException
	 */
	public void modifyCustomerInfo(JSONObject obj, Long customerId) throws CarsmartException {

		if (obj.isNullObject() || obj.isEmpty()) {
			throw new BadRequestException("common", "请求参数不能为空!");
		}

		if (customerId == null || customerId < 0) {
			throw new BadRequestException("400", "请求参数customerId不能为空!");
		}

		Customer customer = passportController.get(customerId);
		Customer update = new Customer();
		update.setId(customerId);
		update.setMobile(customer.getMobile());
		if (obj.containsKey("nickname")) {
			String displayName = obj.optString("nickname", "").trim();
			if (displayName.length() > 6) {
				throw new BadRequestException("common", "昵称超长！");
			}
			update.setNickname(displayName);
		}

		if (obj.containsKey("sex")) {
			String sex = obj.optString("sex", "");
			if (SexEnum.get(sex) == null) {
				throw new BadRequestException("common", "请正确填写性别！");
			}
			update.setSex(SexEnum.get(sex).getIndex() + "");
		}

		if (obj.containsKey("birthday")) {
			String birthday = obj.optString("birthday", "");
			Date birthdayDate = null;
			try {
				birthdayDate = DateUtil.DATEFORMATER2().parse(birthday);
			} catch (ParseException e) {
				throw new BadRequestException("400", "生日格式不正确!");
			}
			update.setBirthday(birthdayDate);
		}

		passportController.updateSelective(update);

	}

	public JSONObject uploadHeadImage(Long customerId, InputStream data, FormDataContentDisposition fileInfo)
			throws CarsmartException {
		// TODO 暂时不做上传头像
		return null;
	}
}
